//
//  SIMySceneViewController.m
//  CampingLight
//
//  Created by Piccolo on 2017/11/26.
//  Copyright © 2017年 SmartIT. All rights reserved.
//

#import "SIMySceneViewController.h"
#import "SIAutoReportInfo.h"
#import "SICPSDKService.h"
#import "UIView+TYAlertView.h"
#import "SIMySceneAlertView.h"
#import "TYAlertController+BlurEffects.h"


@interface SIMySceneViewController () <UITextFieldDelegate> {
    SIAutoReportInfo *_lightAutoReportInfo;
    SIMySceneAlertView *_sceneAlertView;
    TYAlertController *_alertController;
}

@end

@implementation SIMySceneViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupInitialization];
    [self setupNaviBar];
    [self setupSceneDetailView];
    [self setupSceneAlertView];

}

- (void)setupInitialization {
    _sceneDetailView.backgroundColor = LIGHT_GRAY_COLOR_WITH_ALPHA_5;
}

- (NSString *)sceneStringFromIndex:(NSInteger)index {
    
    NSString *bleName = [SICPSDKService getCurrentBle].identityName;
    NSDictionary *customBleDic = [SIUtil userDefaultObjectForKey:bleName];
    
    switch (index) {
        case 1:
            return customBleDic[SmartITFirstSenceName] ? customBleDic[SmartITFirstSenceName] : [SIUtil getSingleKeyStr:@"TEXT_SCENE_ONE"];
        case 2 :
            return customBleDic[SmartITSecondSenceName] ? customBleDic[SmartITSecondSenceName] : [SIUtil getSingleKeyStr:@"TEXT_SCENE_TWO"];
            
        default:
            return @"";
    }
}

- (void)setupSceneAlertView {
    
    _sceneAlertView = [SIMySceneAlertView createViewFromNib];
    _sceneAlertView.layer.cornerRadius = 15.f;
    
    _sceneAlertView.titleLabel.text = [SIUtil getSingleKeyStr:@"TEXT_SAVE_SCENE"];

    [self updateSceneName];
    [_sceneAlertView.firstSceneBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [_sceneAlertView.secondSceneBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    [_sceneAlertView.firstSceneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [_sceneAlertView.secondSceneBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];

    _sceneAlertView.firstSceneBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _sceneAlertView.secondSceneBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _sceneAlertView.firstSceneBtn.layer.borderWidth = .5f;
    _sceneAlertView.secondSceneBtn.layer.borderWidth = .5f;
    _sceneAlertView.firstSceneBtn.layer.cornerRadius = 5.f;
    _sceneAlertView.secondSceneBtn.layer.cornerRadius = 5.f;
    
    [SIUtil addBtn:_sceneAlertView.firstSceneBtn target:self action:@selector(alertViewFirstSceneBtnOnClick:)];
    [SIUtil addBtn:_sceneAlertView.secondSceneBtn target:self action:@selector(alertViewSecondSceneBtnOnClick:)];
    
    UILongPressGestureRecognizer *firstBtnLongPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(firstBtnLongPress:)];
    [_sceneAlertView.firstSceneBtn addGestureRecognizer:firstBtnLongPress];
    
    UILongPressGestureRecognizer *secondBtnLongPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(secondBtnLongPress:)];
    [_sceneAlertView.secondSceneBtn addGestureRecognizer:secondBtnLongPress];
    
    _sceneAlertView.firstTextField.returnKeyType = UIReturnKeyDone;
    _sceneAlertView.secondTextField.returnKeyType = UIReturnKeyDone;
    _sceneAlertView.firstTextField.delegate = self;
    _sceneAlertView.secondTextField.delegate = self;
    [SIUtil addBottomBorderToTextField:_sceneAlertView.firstTextField leftViewText:nil];
    [SIUtil addBottomBorderToTextField:_sceneAlertView.secondTextField leftViewText:nil];
    
    [_sceneAlertView.cancelBtn setTitle:[SIUtil getSingleKeyStr:@"TEXT_CANCEL"] forState:UIControlStateNormal];
    [_sceneAlertView.saveBtn setTitle:[SIUtil getSingleKeyStr:@"TEXT_SAVE"] forState:UIControlStateNormal];
    
    [_sceneAlertView.cancelBtn setTintColor:[UIColor redColor]];
    
    [SIUtil addBtn:_sceneAlertView.cancelBtn target:self action:@selector(alertViewCancelBtnOnClick:)];
    [SIUtil addBtn:_sceneAlertView.saveBtn target:self action:@selector(alertViewSaveBtnOnClick:)];
    
    [self updateSceneAlertViewSaveBtnEnabled];
    _alertController = [TYAlertController alertControllerWithAlertView:_sceneAlertView preferredStyle:TYAlertControllerStyleAlert];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSString * searchStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSLog(@"@110%@",searchStr);
    if (searchStr.length > 8) {
        return NO;
    }
    return YES;
}
//
//- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
//
//    [textField resignFirstResponder];
//    if (textField == _sceneAlertView.firstTextField) {
//        _sceneAlertView.firstSceneBtn.hidden = NO;
//        [SIUtil setUserDefaultObject:textField.text forKey:SmartITFirstSenceName];
//    } else if (textField == _sceneAlertView.secondTextField) {
//        _sceneAlertView.firstSceneBtn.hidden = NO;
//        [SIUtil setUserDefaultObject:textField.text forKey:SmartITSecondSenceName];
//    }
//    return YES;
//}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    textField.hidden = YES;
    NSString *bleName = [SICPSDKService getCurrentBle].identityName;
    NSMutableDictionary *muCustomBleDic = [SIUtil userDefaultObjectForKey:bleName] ? [NSMutableDictionary dictionaryWithDictionary:[SIUtil userDefaultObjectForKey:bleName]] : [NSMutableDictionary new];
    if (textField == _sceneAlertView.firstTextField) {
        _sceneAlertView.firstSceneBtn.hidden = NO;
        [muCustomBleDic setObject:textField.text forKey:SmartITFirstSenceName];
//        [SIUtil setUserDefaultObject:textField.text forKey:SmartITFirstSenceName];
    } else if (textField == _sceneAlertView.secondTextField) {
        _sceneAlertView.secondSceneBtn.hidden = NO;
        [muCustomBleDic setObject:textField.text forKey:SmartITSecondSenceName];
//        [SIUtil setUserDefaultObject:textField.text forKey:SmartITSecondSenceName];
    }
    [SIUtil setUserDefaultObject:muCustomBleDic forKey:bleName];
    [self updateSceneName];
    if (_sceneAlertView.firstTextField.hidden && _sceneAlertView.secondTextField.hidden) {
        [SIUtil setBtn:_sceneAlertView.saveBtn enabled:YES];
        [SIUtil setBtn:_sceneAlertView.cancelBtn enabled:YES];
    }
    return YES;
}

- (void)updateSceneName {
    
    NSString *firstSceneNameString = [self sceneStringFromIndex:1];
    _firstSceneLabel.text = firstSceneNameString;
    [_sceneAlertView.firstSceneBtn setTitle:firstSceneNameString forState:UIControlStateNormal];
    [_sceneAlertView.firstSceneBtn setTitle:firstSceneNameString forState:UIControlStateSelected];
    
    NSString *secondSceneNameString = [self sceneStringFromIndex:2];
    _secondSceneLabel.text = secondSceneNameString;
    [_sceneAlertView.secondSceneBtn setTitle:secondSceneNameString forState:UIControlStateNormal];
    [_sceneAlertView.secondSceneBtn setTitle:secondSceneNameString forState:UIControlStateSelected];
}

- (void)setupNaviBar {
    
    /*Left Navi bar btn*/
    
    self.navigationItem.title = [SIUtil getSingleKeyStr:@"TEXT_MY_SCENE"];
    UIBarButtonItem *backItem = [SIUtil newBarItemWithImageName:@"ico-back.png" target:self action:@selector(backBtnOnClick:)];
    self.navigationItem.leftBarButtonItem = backItem;
    
    /*Right Navi bar btn*/

    UIBarButtonItem *settingBtnItem = [SIUtil newBarItemWithImageName:@"icon-set-64.png" target:self action:@selector(settingBtnOnClick:)];
    self.navigationItem.rightBarButtonItems = @[settingBtnItem];
}

- (void)setupSceneDetailView {
    [SIUtil setBtn:_readingBtn
                imageName:nil
          needRoundCorner:YES
                   target:self
                   action:@selector(readingBtnOnClick:)];
    [SIUtil setBtn:_sleepingBtn
                imageName:nil
          needRoundCorner:YES
                   target:self
                   action:@selector(sleepingBtnOnClick:)];
    [SIUtil setBtn:_firstSceneBtn
                imageName:nil
          needRoundCorner:YES
                   target:self
                   action:@selector(firstSceneBtnOnClick:)];
    [SIUtil setBtn:_secondSceneBtn
                imageName:nil
          needRoundCorner:YES
                   target:self
                   action:@selector(secondSceneBtnOnClick:)];
    
    _readingLabel.text = [SIUtil getSingleKeyStr:@"TEXT_READING"];
    _sleepingLabel.text = [SIUtil getSingleKeyStr:@"TEXT_SLEEPING"];
    [self updateSceneName];
}

- (void)updateSceneAlertViewSaveBtnEnabled {
    [SIUtil setBtn:_sceneAlertView.saveBtn enabled:_sceneAlertView.firstSceneBtn.selected || _sceneAlertView.secondSceneBtn.selected];
    _sceneAlertView.firstSceneBtn.backgroundColor = _sceneAlertView.firstSceneBtn.selected ? [UIColor blueColor] : [UIColor whiteColor];
    _sceneAlertView.secondSceneBtn.backgroundColor = _sceneAlertView.secondSceneBtn.selected ? [UIColor blueColor] : [UIColor whiteColor];

}


/*--Navi Btn--*/

- (void)backBtnOnClick:(UIButton *)btn {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)settingBtnOnClick:(UIButton *)btn {
    // blur effect
//    [alertController setBlurEffectWithView:self.view];
    
    //alertController.alertViewOriginY = 60;
    [self presentViewController:_alertController animated:YES completion:nil];
}

/*--Scene Btn--*/

- (void)readingBtnOnClick:(UIButton *)btn {
    [self setCampingLightType:NSSISceneTypeReading];
}

- (void)sleepingBtnOnClick:(UIButton *)btn {
    [self setCampingLightType:NSSISceneTypeSleeping];
}

- (void)firstSceneBtnOnClick:(UIButton *)btn {
    [self setCampingLightType:NSSISceneTypeScene1];
}

- (void)secondSceneBtnOnClick:(UIButton *)btn {
    [self setCampingLightType:NSSISceneTypeScene2];
}

/*--Scene Alert Btn--*/
- (void)alertViewCancelBtnOnClick:(UIButton *)btn {
    [_sceneAlertView hideView];
}

- (void)alertViewSaveBtnOnClick:(UIButton *)btn {
    SILightInfo *currentLightInfo = [_lightAutoReportInfo.lightInfo copy];
    if (_sceneAlertView.firstSceneBtn.selected) {
        [SIUtil setUserDefaultCampingLightInfo:currentLightInfo toSceneType:NSSISceneTypeScene1];
    } else if (_sceneAlertView.secondSceneBtn.selected) {
        [SIUtil setUserDefaultCampingLightInfo:currentLightInfo toSceneType:NSSISceneTypeScene2];
    }
    [_sceneAlertView hideView];
}

- (void)alertViewFirstSceneBtnOnClick:(UIButton *)btn {
    _sceneAlertView.secondSceneBtn.selected = NO;
    btn.selected = !btn.selected;
    [self updateSceneAlertViewSaveBtnEnabled];
}

- (void)alertViewSecondSceneBtnOnClick:(UIButton *)btn {
    _sceneAlertView.firstSceneBtn.selected = NO;
    btn.selected = !btn.selected;
    [self updateSceneAlertViewSaveBtnEnabled];
}

- (void)firstBtnLongPress:(UILongPressGestureRecognizer *)reg {
    
    _sceneAlertView.firstSceneBtn.hidden = YES;
    _sceneAlertView.firstTextField.hidden = NO;
    [SIUtil setBtn:_sceneAlertView.saveBtn enabled:NO];
    [SIUtil setBtn:_sceneAlertView.cancelBtn enabled:NO];
    [_sceneAlertView.firstTextField becomeFirstResponder];
}

- (void)secondBtnLongPress:(UILongPressGestureRecognizer *)reg {

    _sceneAlertView.secondSceneBtn.hidden = YES;
    _sceneAlertView.secondTextField.hidden = NO;
    [SIUtil setBtn:_sceneAlertView.saveBtn enabled:NO];
    [SIUtil setBtn:_sceneAlertView.cancelBtn enabled:NO];
    [_sceneAlertView.secondTextField becomeFirstResponder];
}

- (void)updateSceneView {
    
    SILightInfo *lightInfo = [_lightAutoReportInfo.lightInfo copy];
    
    BOOL isReadingScene = [SIUtil checkCampingLightInfo:lightInfo isType:NSSISceneTypeReading];
    BOOL isSleepingScene = [SIUtil checkCampingLightInfo:lightInfo isType:NSSISceneTypeSleeping];
    BOOL isFirstCustomScene = [SIUtil checkCampingLightInfo:lightInfo isType:NSSISceneTypeScene1];
    BOOL isSecondCustomScene = [SIUtil checkCampingLightInfo:lightInfo isType:NSSISceneTypeScene2];
    
    [SIUtil setBtn:_readingBtn selected:isReadingScene];
    [SIUtil setBtn:_sleepingBtn selected:isSleepingScene];
    [SIUtil setBtn:_firstSceneBtn selected:isFirstCustomScene];
    [SIUtil setBtn:_secondSceneBtn selected:isSecondCustomScene];
    
    [SIUtil setBtn:_firstSceneBtn enabled:[SIUtil sceneExist:NSSISceneTypeScene1]];
    [SIUtil setBtn:_secondSceneBtn enabled:[SIUtil sceneExist:NSSISceneTypeScene2]];
    
}
#pragma mark - SmartITMyDeviceViewControllerFuntion
- (void)updateAutoReport:(SICPSDKResultInfo *)activeReportInfo {
    if ([SIUtil isExistDic:activeReportInfo.detailDic key:@"auto_basic_report_data"]) {
        _lightAutoReportInfo = [[SIAutoReportInfo alloc] initWithSmartITCampingLightAutoReportInfoData:activeReportInfo.detailDic[@"auto_basic_report_data"]];
    }
//    if ([SIUtil isExistDic:activeReportInfo.detailDic key:@"auto_current_report_data"]) {
//        [_lightAutoReportInfo updateWithSmartITCampingLightCurrentReportInfoData:activeReportInfo.detailDic[@"auto_current_report_data"]];
//        NSLog(@"@这里来了");
//    }
    [self updateSceneView];
    
    //    if (!_timer) {
    //        [self updateOperationViewController];
    //    }
}

- (void)bleDisconnect {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setCampingLightType:(NSSISceneType)sceneType {
    
//    switch (sceneType) {
//        case NSSISceneTypeScene1:
//            if (![SIUtil sceneExist:NSSISceneTypeScene1]) {
//                return;
//            }
//        case NSSISceneTypeScene2:
//            if (![SIUtil sceneExist:NSSISceneTypeScene2]) {
//                return;
//            }
//        default:
//            break;
//    }
    SILightInfo *currentLightInfo = [_lightAutoReportInfo.lightInfo copy];
    SILightInfo *resultLightInfo = [SIUtil lightInfoFromSceneType:sceneType currentLightInfo:currentLightInfo];
    [SICPSDKService sendSettingBasicInfoFromLightInfo:resultLightInfo];
}
@end
